package com.chinaoct.siku.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
public class FileUtil {
    public static String getContentType(String fileType) {
        if("jpe".equalsIgnoreCase(fileType.trim())) return "image/jpeg";
        if("jpeg".equalsIgnoreCase(fileType.trim())) return "image/jpeg";
        if("jpg".equalsIgnoreCase(fileType.trim())) return "image/jpeg";
        if("gif".equalsIgnoreCase(fileType.trim())) return "image/gif";
        if("png".equalsIgnoreCase(fileType.trim())) return "image/png";
        if("zip".equalsIgnoreCase(fileType.trim())) return "application/zip";
        if("pdf".equalsIgnoreCase(fileType.trim())) return "application/pdf";
        if("doc".equalsIgnoreCase(fileType.trim())) return "application/msword";
        if("xls".equalsIgnoreCase(fileType.trim())) return "application/vnd.ms-excel";
        if("ppt".equalsIgnoreCase(fileType.trim())) return "application/vnd.ms-powerpoint";
        if("docx".equalsIgnoreCase(fileType.trim())) return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        if("pptx".equalsIgnoreCase(fileType.trim())) return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        if("xlsx".equalsIgnoreCase(fileType.trim())) return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if("zip".equalsIgnoreCase(fileType.trim())) return "application/zip";
        if("rar".equalsIgnoreCase(fileType.trim())) return "application/octet-stream";

        if("bmp".equalsIgnoreCase(fileType.trim())) return "image/bmp";
        if("pbm".equalsIgnoreCase(fileType.trim())) return "image/x-portable-bitmap";
        if("pct".equalsIgnoreCase(fileType.trim())) return "image/pict";
        if("pgm".equalsIgnoreCase(fileType.trim())) return "image/x-portable-graymap";
        if("pic".equalsIgnoreCase(fileType.trim())) return "image/pict";
        if("pict".equalsIgnoreCase(fileType.trim())) return "image/pict";
        if("pnm".equalsIgnoreCase(fileType.trim())) return "image/x-portable-anymap";
        if("psd".equalsIgnoreCase(fileType.trim())) return "image/x-photoshop";
        if("dib".equalsIgnoreCase(fileType.trim())) return "image/bmp";
        if("ico".equalsIgnoreCase(fileType.trim())) return "image/x-icon";
        if("ief".equalsIgnoreCase(fileType.trim())) return "image/ief";
        if("mac".equalsIgnoreCase(fileType.trim())) return "image/x-macpaint";
        if("tif".equalsIgnoreCase(fileType.trim())) return "image/tiff";
        if("tiff".equalsIgnoreCase(fileType.trim())) return "image/tiff";
        if("wbmp".equalsIgnoreCase(fileType.trim())) return "image/vnd.wap.wbmp";

        return "application/octet-stream";
    }


        /**
         * 下载项目根目录下doc下的文件
         * @param response response
         * @param file 文件
         * @return 返回结果 成功或者文件不存在
         */
    public static void downloadFile(HttpServletResponse response, File file,String fileType) throws Exception {

        String fileName=file.getName();

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        response.setContentType(getContentType(fileType));
        response.setHeader("Content-disposition", "attachment; filename="
                + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
        response.setHeader("Content-Length", String.valueOf(file.length()));

        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        } finally {
            if(bis != null) bis.close();
            if(bos != null) bos.close();
        }
    }

    /**
     * 下载项目根目录下doc下的文件
     * @param response response
     * @param file 文件
     * @return 返回结果 成功或者文件不存在
     */
    public static String downloadFile(HttpServletResponse response, File file) {

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (FileNotFoundException e1) {
            //e1.getMessage()+"系统找不到指定的文件";
            return "系统找不到指定的文件";
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "success";
    }


    /**
     * 响应体加入文件流
     * @param response
     * @param file	文件从盘符开始的完整路径
     */
    public static void responseFileStream(HttpServletResponse response, File file){


        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            String fileName =file.getName();
            String[] array = fileName.split("[.]");
            String fileType = array[array.length-1].toLowerCase();
            //设置文件ContentType类型
            if("jpg,jepg,gif,png".contains(fileType)){//图片类型
                response.setContentType("image/"+fileType);
            }else if("pdf".contains(fileType)){//pdf类型
                response.setContentType("application/pdf");
            }else{//自动判断下载文件类型
                response.setContentType("multipart/form-data");
            }
            //设置文件头：最后一个参数是设置下载文件名
            //response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            log.error("responseFileStream error:FileNotFoundException" + e.toString());
        } catch (Exception e) {
            log.error("responseFileStream error:" + e.toString());
        } finally {
            try {
                out.close();
                in.close();
            } catch (NullPointerException e) {
                log.error("responseFileStream stream close() error:NullPointerException" + e.toString());
            } catch (Exception e) {
                log.error("responseFileStream stream close() error:" + e.toString());
            }
        }
    }

    /**
     * @param file
     * @return
     * @throws IOException
     * @author jiangzeyin
     * @date 2016-8-17
     */
    public static FileType getFileType(File file) throws IOException {
        byte[] src = new byte[28];
        FileInputStream is =null;
        try {
            is =new FileInputStream(file);
            is.read(src, 0, 28);
            StringBuilder stringBuilder = new StringBuilder("");
            if (src == null || src.length <= 0) {
                return null;
            }
            for (int i = 0; i < src.length; i++) {
                int v = src[i] & 0xFF;
                String hv = Integer.toHexString(v).toUpperCase();
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }
                stringBuilder.append(hv);
            }
            FileType[] fileTypes = FileType.values();
            for (FileType fileType : fileTypes) {
                if (stringBuilder.toString().startsWith(fileType.getValue())) {
                    return fileType;
                }
            }
            return null;
        }finally {
            if(null!=is){
                is.close();
            }
        }

    }


    public static File multipartFileToFile(MultipartFile file ) throws Exception {

        File toFile = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    public static String checkType(String xxx) {
        switch (xxx) {
            case "FFD8FF": return "jpg";
            case "89504E": return "png";
            case "474946": return "jif";
            case "D0CF11": return "xls";
            case "504B03": return "xlsx";
            case "D0CF11E0": return "Word/Excel";
            default: return "0000";
        }
    }
}
